package com.learn.job;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author : Yu.Tan
 * @date : 2023/3/23 10:59
 * @desc : **
 */
public class JdkJob {

    public static void main(String[] args) {
        List<String> tasks = new ArrayList<>();
        tasks.add("00001");
        tasks.add("00002");
        tasks.add("00003");
        tasks.add("00004");
        tasks.add("00005");
        DelayQueue<JdkDelay> queue = new DelayQueue<JdkDelay>();

        long start = System.currentTimeMillis();

        for (int i = 0; i < 5; i++) {
            //延迟三秒取出
            queue.put(new JdkDelay(tasks.get(i), TimeUnit.NANOSECONDS.convert(5, TimeUnit.SECONDS)));
            try {
                queue.take().print();
                System.out.println("After " + (System.currentTimeMillis() - start) + " MilliSeconds");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    static class JdkDelay implements Delayed {

        private String orderId;

        private long timeout;

        public JdkDelay(String orderId, long timeout) {
            this.orderId = orderId;
            this.timeout = timeout;
        }

        /**
         * 返回距离你自定义的超时时间还有多少
         *
         * @param unit
         * @return
         */
        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(timeout - System.nanoTime(), TimeUnit.NANOSECONDS);
        }

        @Override
        public int compareTo(Delayed other) {
            if (other == this) {
                return 0;
            }
            JdkDelay t = (JdkDelay) other;
            long d = (getDelay(TimeUnit.NANOSECONDS) - t.getDelay(TimeUnit.NANOSECONDS));
            return (d == 0) ? 0 : ((d < 0) ? -1 : 1);

        }

        void print() {
            System.out.println(orderId + "编号的订单要删除啦。。。。");
        }
    }
}
